import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flutter/material.dart';
import 'package:flutter_flame/worlds/game/state/SeedSelectionState.dart';
import 'package:flutter_flame/config/AssetsName.dart';
import 'package:flutter_flame/component/SpriteEntity.dart';
import 'SeedChooserBank.dart';
import 'SeedPacket.dart';
import 'StartButtonBackground.dart';
import '../TextSelectYourPlant.dart';
import 'StartButton.dart';
import 'SeedPacketSilhouette.dart';

/// 植物种子商店背景
class SeedChooserBackground extends SpriteEntity {
  SeedChooserBackground({required this.state})
      : super(AssetsName.spriteSeedChooserBackground);

  static const double _yOffset = -85;
  static const double _width = 560.0;

  late StartButtonBackground startButtonBackground;
  late Vector2 initPosition;
  late SeedSelectionState state;

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    _initPositionAndSize();
    _addUIComponents();
  }

  // 初始化位置
  void _initPositionAndSize() {
    final radio = sprite!.image.width / sprite!.image.height;
    position = Vector2(0, _yOffset + _width / radio);
    initPosition = Vector2(0, _yOffset + _width / radio);
    setSize(_width);
  }

  // 组件
  void _addUIComponents() {
    startButtonBackground = StartButtonBackground(position.y);
    add(startButtonBackground);
    add(StartButton(position.y, state, completeSelectSeeds));
    add(TextSelectYourPlant());
  }

  /// 移入到镜头中
  void moveIn(VoidCallback display) {
    add(
      MoveToEffect(
        Vector2(0, _yOffset),
        EffectController(duration: 0.4, curve: Curves.easeInOut),
        onComplete: () {
          display();
        },
      ),
    );
  }

  /// 完成选择，清理现场
  void completeSelectSeeds() {
    final seedChooserBank = parent as SeedChooserBank;
    add(
      MoveToEffect(
        initPosition,
        EffectController(duration: 0.4, curve: Curves.easeInOut),
        onComplete: () {
          removeFromParent();
          seedChooserBank.onCompleted();
        },
      ),
    );
    // 移除未选中的和阴影
    seedChooserBank.children
        .whereType<SeedPacket>()
        .where((e) =>
            e.showShadow || !e.seedModel.isSelected || e.isSeedBackground)
        .forEach((e) => e.removeFromParent());
    // 透明度隐藏
    seedChooserBank.children
        .whereType<SeedPacket>()
        .where((e) => e.seedModel.isSelected)
        .forEach((e) => e.selectableTransformDraggableMenu());
    // 隐藏卡槽
    seedChooserBank.children.whereType<SeedPacketSilhouette>().forEach(
          (e) => e.removeFromParent(),
        );
  }
}
